package cn.kgc.service;

import cn.kgc.client.RestDmOrderClient;
import cn.kgc.client.RestDmSchedulerSeatClient;
import cn.kgc.client.RestDmTradeClient;
import cn.kgc.exception.PayErrorCode;
import cn.kgc.pojo.DmOrder;
import cn.kgc.pojo.DmSchedulerSeat;
import cn.kgc.pojo.DmTrade;
import cn.kgc.utils.BaseException;
import cn.kgc.utils.Constants;
import com.netflix.discovery.converters.Auto;
import io.netty.util.Constant;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
public class DmTradeServiceImpl implements DmTradeServcie{

    @Autowired
    RestDmOrderClient restDmOrderClient;


    @Autowired
    RestDmSchedulerSeatClient restDmSchedulerSeatClient;


    @Autowired
    RestDmTradeClient restDmTradeClient;

    @Autowired
    RabbitTemplate rabbitTemplate;



    @Override
    public boolean processedPay(String out_trade_no, int zhifubao) throws Exception {
        return restDmOrderClient.processedPay(out_trade_no,zhifubao);
    }

    @Override
    public void changeTradeStatus(String out_trade_no, String trade_no, int type) throws Exception {
        //1。订单表的订单状态的修改
        java.util.Map<String,Object> map =new HashMap<>();
        map.put("orderNo",out_trade_no);
        DmOrder dmOrder = restDmOrderClient.getDmOrderListByMap(map).get(0);
        if(dmOrder.getOrderType()==2){
            return;
        }
        if(type==Constants.PayMethod.ZHIFUBAO){
            dmOrder.setAliTradeNo(trade_no);
            dmOrder.setPayType(Constants.PayMethod.ZHIFUBAO+"");
            dmOrder.setCreatedTime(new java.util.Date());
        }else{
            dmOrder.setWxTradeNo(trade_no);
            dmOrder.setPayType(Constants.PayMethod.WEIXIN+"");
            dmOrder.setCreatedTime(new java.util.Date());
        }
        dmOrder.setOrderType(Constants.OrderStatus.SUCCESS);
        Integer result = restDmOrderClient.qdtxModifyDmOrder(dmOrder);
        if(result==null){
            throw new BaseException(PayErrorCode.DB_ERROR);
        }

        //2. 排期座位的状态的修改
        try{
            List<DmSchedulerSeat> dmSchedulerSeatListByMap = restDmSchedulerSeatClient.getDmSchedulerSeatListByMap(map);
            for (DmSchedulerSeat dmSchedulerSeat : dmSchedulerSeatListByMap) {
                dmSchedulerSeat.setStatus(Constants.SchedulerSeatStatus.SchedulerSeat_PAYSUCCESS);
                dmSchedulerSeat.setUpdatedTime(new java.util.Date());

                result = restDmSchedulerSeatClient.qdtxModifyDmSchedulerSeat(dmSchedulerSeat);
                if (result==null){
                    throw new BaseException(PayErrorCode.DB_ERROR);
                }
                int i=0;
                i=5/i;
            }
        }catch (Exception e){
            //事务回滚，
            //订单状态的修改--->事务回滚--》改成未支付状态 todo  分布式事务需要你们下去完成，仿造下订单模块实现
            sendUpdateOrderState(out_trade_no);
            //重置座位的回滚 todo  分布式事务需要你们下去完成，仿造下订单模块实现
            throw  e;
        }
        //3.插入数据到交易表中
        DmTrade trade = new DmTrade();
        trade.setOrderNo(out_trade_no);
        trade.setTradeNo(trade_no);
        trade.setPayMethod(type);
        trade.setAmount(dmOrder.getTotalAmount());
        trade.setCreatedTime(new Date());
        try{
            result = restDmTradeClient.qdtxAddDmTrade(trade);
            if (result==null){
                throw new BaseException(PayErrorCode.DB_ERROR);
            }
        }catch (Exception e){
            //事务回滚
            //订单状态的修改--->事务回滚--》改成未支付状态
            sendUpdateOrderState(out_trade_no);
            //座位状态的修改--->事务回滚--> 座位从已售出改成锁定待付款状态 todo  分布式事务需要你们下去完成，仿造下订单模块实现

            throw  e;
        }

    }

    private void sendUpdateOrderState(String out_trade_no) {
        rabbitTemplate.convertAndSend(Constants.RabbitQueueName.TOPIC_EXCHANGE, Constants.RabbitQueueName.TO_UPDATE_ORDER_STATE, out_trade_no, new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
                return message;
            }
        });

    }
}
